package com.demo.kafka.config;

import jakarta.annotation.Resource;
import org.apache.kafka.clients.consumer.ConsumerConfig;
import org.apache.kafka.common.serialization.StringDeserializer;
import org.springframework.boot.autoconfigure.kafka.KafkaProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.kafka.config.ConcurrentKafkaListenerContainerFactory;
import org.springframework.kafka.core.DefaultKafkaConsumerFactory;
import org.springframework.kafka.listener.ContainerProperties;

import java.util.HashMap;
import java.util.Map;

/**
 * Kafka客户端配置
 * @author cyj
 */
@Configuration
public class KafkaConfig {

    @Resource
    private KafkaProperties properties;

    /**
     * 定义消费者配置，跟配置文件里的配置是隔离，互不影响
     * @return ConcurrentKafkaListenerContainerFactory
     */
    @Bean("myKafkaListenerContainerFactory")
    public ConcurrentKafkaListenerContainerFactory<String, String> kafkaListenerContainerFactory() {
        Map<String, Object> map = new HashMap<>();
        map.put(ConsumerConfig.KEY_DESERIALIZER_CLASS_CONFIG, StringDeserializer.class);
        map.put(ConsumerConfig.VALUE_DESERIALIZER_CLASS_CONFIG, StringDeserializer.class);
        // 每次消费拉取100条消息
        map.put(ConsumerConfig.MAX_POLL_RECORDS_CONFIG, 100);
        // broker 地址
        map.put(ConsumerConfig.BOOTSTRAP_SERVERS_CONFIG, properties.getBootstrapServers());

        ConcurrentKafkaListenerContainerFactory<String, String> factory = new ConcurrentKafkaListenerContainerFactory<>();
        factory.setConsumerFactory(new DefaultKafkaConsumerFactory<>(map));
        // 并发消费
        factory.setConcurrency(5);
        // 拉取消息超时时间
        factory.getContainerProperties().setPollTimeout(2000);
        // 手动ack
        factory.getContainerProperties().setAckMode(ContainerProperties.AckMode.MANUAL);
        // 设置为批量消费，每个批次数量在Kafka配置参数中设置ConsumerConfig.MAX_POLL_RECORDS_CONFIG
        factory.setBatchListener(true);

        return factory;
    }
}
